package com.example.a1.sharedpreferencestest322jzy;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.Toast;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


public class MainActivity extends AppCompatActivity {
    @BindView(R.id.editText)
    EditText etname;
    @BindView(R.id.editText2)
    EditText etpass;
    @BindView(R.id.switch1)
    Switch sw;
    String username, password;
    SharedPreferences login;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        login = getSharedPreferences("login", MODE_PRIVATE);
        readlogin();
    }

    private void readlogin() {
        String name = login.getString("username",null);
        String pass = login.getString("password",null);
        Boolean isRemember = login.getBoolean("remember",false);
        if (isRemember){
            etname.setText(name);
            etpass.setText(pass);
        }
    }

    @OnClick(R.id.btnlogin)
    public void btnLoginOncliked() {
        username = etname.getText().toString();
        password = etpass.getText().toString();
        if (username.equals("jzy") && password.equals("111")) {
            Toast.makeText(this, "登陆成功", Toast.LENGTH_SHORT).show();
            savelogin();
        }
    }

    private void savelogin() {
        SharedPreferences.Editor editor = login.edit();
        editor.putString("username",username);
        editor.putString("password",password);
        editor.putBoolean("remember",sw.isChecked());
        editor.apply();//提交保存
    }


}
